var ctr_load_starred = 10;
var continueToLoad_starred = true;
var continueToLoad_starred_page = true;
$(document).ready(function(){
    var pathname = window.location.pathname;
    var objStarred = {"type":"0"};
    var objMyRequest = {"type":"0"};
    if(
        pathname!="/organizational_chart" &&
        pathname!="/workflow" &&
        pathname!="/formbuilder"
    ){
        
        Starred.load(0,"start",objStarred,function(result){
            Starred.loadAfterAjaxStarredWidget(result);
            MyRequest.load(0,"start",objMyRequest,function(result_myrequest){
                $(".sub-container-mr").html(result_myrequest);

                if(result_myrequest.length>0 && $(".sm-myr").length==0){
                    $("#my-request-container").append("<div class='sm-myr' style='margin-top: 50px;padding: 0px 0px 10px 0px;text-align:center;font-weight: bold;'><a href='/my_request'>See All</a></div>");
                }
                $("#my-request-container").perfectScrollbar("update");
            });
	    
        });
    }
    //widget user view
    if(pathname=="/user_view/home"){
        var objStarred_user_widget = {"type":"2"};
        $(".starredUserWidgetWrapper").closest(".fl-widget").find(".fl-widget-wrapper-center-content").show();
        $(".starredUserWidgetWrapper").closest(".fl-widget").find(".fl-loading-content").fadeIn();
        Starred.load(0,"start",objStarred_user_widget,function(result){
            $(".starredUserWidget").html(result)
            widgetUserSeeMore(".starredUserWidget","/user_view/starred")
            Starred.count();
            $(".starredUserWidgetWrapper").perfectScrollbar("destroy");
            
            $(".starredUserWidgetWrapper").closest(".fl-widget").find(".fl-loading-content").fadeOut();
            $(".starredUserWidgetWrapper").closest(".fl-widget").find(".fl-widget-wrapper-center-content").hide();
            if(result==""){
                $(".starredUserWidgetWrapper").closest(".fl-widget").find(".fl-no-data-found").fadeIn();
            }
	    posting.loadEvent();
	    $(".starredUserWidgetWrapper").perfectScrollbar();
        })

        $(".starredUserWidgetWrapper").scroll(function() {
            var scroll_diff = $(this).scrollTop() - ($(this).find(".starredUserWidget").outerHeight() - $(this).outerHeight());
            // console.log((scroll_diff+" >= "+(-2))+" && "+(scroll_diff+" <= "+2))
            if ((scroll_diff >= -20) && (scroll_diff <= 22)) {
                if(continueToLoad_starred==true){
                    Starred.load(ctr_load_starred,"load",objStarred_user_widget,function(result){
                        if(result.length>0){
                            ctr_load_starred+=10;
                            continueToLoad_starred = true;
                            $(".starredUserWidget").append(result);
                            $(".starredUserWidgetWrapper").perfectScrollbar("destroy");
                            $(".starredUserWidgetWrapper").perfectScrollbar();
                        }
                        widgetUserSeeMore(".starredUserWidget","/user_view/starred")
                    }); 
                }
            }
        });
    }
    // alert(123)
    //end widget user view
    $("body").on("click",".search-starred",function(){
        Starred.load(0,"start",objStarred,function(result){
           $(".starred-wrapper").html(result);
        });
    })
    $("body").on("keydown",".search-starred-value",function(e){
        if (e.keyCode == "13") {
            Starred.load(0,"start",objStarred,function(result){
               $(".starred-wrapper").html(result);
            });
        }
    })
	//hover in and hover out on starred
	$("body").on("mouseenter",".starred",function(){
		Starred.hoverIn(this);
	});
	$("body").on("mouseleave",".starred",function(){
		Starred.hoverOut(this);
	});
    $("body").on("mouseenter",".starred-row",function(){
        $(this).find(".removeStarred").css({
            "display":"block"   
        })
    })
    $("body").on("mouseleave",".starred-row",function(){
        $(this).find(".removeStarred").css({
            "display":"none"   
        })
    })
	$("body").on("click",".starred",function(){
        var id = this.id;
		Starred.updateData(this,id);
        Starred.load(0,"start",objStarred,function(result){
            Starred.loadAfterAjaxStarredWidget(result);
        });
	})
    $("body").on("click",".removeStarred, .removeStarred_user, .removeStarred_user_widget",function(){
        var id = $(this).attr("counterPart-id");
        Starred.updateData(this,id);
        Starred.load(0,"start",objStarred,function(result){
            Starred.loadAfterAjaxStarredWidget(result);
            $(".fl-starred-container-users").perfectScrollbar("destroy");
            $(".fl-starred-container-users").perfectScrollbar();
        });
    })
    //count starred
     Starred.count();
    // $("#starred-container").scroll(function(){
    //     var pads = 12; //padding
    //     if($(this).scrollTop() == $(this).find(".sub-container-starred").height() - $(this).height()){ 
    //        // for load request

    //        if(continueToLoad_starred==true){
    //             Starred.load(ctr_load_starred,"load",function(){
    //                 ctr_load_starred+=10;
    //             }); 
    //        }
    //     }
    // })
    var pathname = window.location.pathname;
    if(pathname=="/user_view/starred"){
        objStarred_user = {"type":1};
        $(".starred-notif").fadeIn();
        $(".fl-loading-content").fadeIn();
        Starred.load(0,"start",objStarred_user,function(result){
            $(".starred-wrapper2").html(result);
            $(".fl-starred-wrapper-scroll").perfectScrollbar("destroy");
            $(".fl-starred-container-users").perfectScrollbar();
            if(result==""){
                $(".fl-no-record-found").fadeIn();
            }
            $(".fl-loading-content").fadeOut();
        })
        $(".fl-starred-container-users").scroll(function() {
            var scroll_diff = $(this).scrollTop() - ($(this).find(".fl-starred-wrapper-scroll").height() - $(this).height());
            // console.log(scroll_diff)
            // console.log((scroll_diff+" >= "+(-2))+" && "+(scroll_diff+" <= "+2))
            if ((scroll_diff >= -2) && (scroll_diff <= 2)) {
                if(continueToLoad_starred==true){
                    Starred.load(ctr_load_starred,"load",objStarred_user,function(result){
                        if(result.length>0){
                            ctr_load_starred+=10;
                            continueToLoad_starred = true;
                            $(".starred-wrapper2").append(result);
                            $(".fl-starred-container-users").perfectScrollbar("destroy");
                            $(".fl-starred-container-users").perfectScrollbar();
                        }
                    }); 
                }
            }
        });
    }
    if(pathname=="/starred"){
        Starred.load(0,"start",objStarred,function(result){
            $(".starred-wrapper").html(result);
        })
        $(window).scroll(function() {
            var scroll_diff = $(window).scrollTop() - ($(document).height() - $(window).height());
            // console.log(scroll_diff)
            // console.log((scroll_diff+" >= "+(-1))+" && "+(scroll_diff+" <= "+1))
            if ((scroll_diff >= -2) && (scroll_diff <= 2)) {
                if(continueToLoad_starred==true){
                    Starred.load(ctr_load_starred,"load",objStarred,function(result){
                        if(result.length>0){
                            ctr_load_starred+=10;
                            continueToLoad_starred = true;
                            $(".starred-wrapper").append(result);
                        }
                    }); 
                }
            }
        });
    }
})
Starred = {
    load : function(start,status,obj,callback){
        continueToLoad_starred = false;
        var search_value = $(".search-starred-value").val();
        var self = this;
        if($(".starred-wrapper").find(".load-app-starred").length==0){
            $(".starred-wrapper").append('<center><img src="/images/loader/loader.gif" class="load-app-starred" style="display: inline;"></center>');
        }
        
        $.post("/ajax/starred",{action:"loadData",start:start,search_value:search_value},function(data){
            // console.log(data);
            // return;
            var data = JSON.parse(data);
            var result = "";
            if(obj['type']==0){
                result = self.view(data);
            }else if(obj['type']==1){
                result = self.view2(data);
            }else if(obj['type']==2){
                result = self.view3(data);
            }
           
            if(status=="start"){
                //restore variables for load more
                // $(".sub-container-starred").html(result);
                // $(".starred-wrapper").html(result);
                
                ctr_load_starred = 10;
                continueToLoad_starred = true;
                // if(data.length>0 && $(".sm-sr").length==0){
                //     $(".sub-container-starred").append("<div class='sm-sr' style='margin-top: -5px;padding: 0px 0px 10px 0px;text-align:center;font-weight: bold;'><a href='/starred'>See All</a></div>");
                // }
                
            }else if(status == "load"){
                // $(".starred-wrapper").append(result);
                // $(".sub-container-starred").append(result);
                // $("#starred-container").perfectScrollbar("update");
            }
            $(".timeago").timeago();
            $(".load-app-starred").remove();
            callback(result)
        })

        // .fail(function(){
        //     alert("CONNECTION FAILED!!");
        //     continueToLoad_starred = false;
        // })
    },
    view : function(data){
        var ret = "";
        var stat = "";
        if(data.length==0){
            continueToLoad_starred = false;
        }else{
            // $.each(data,function(key, request){

            var requestor_id = "";
            var padding = "";
            var link = "";
            var icon = "";
            for(var i in data){
                if(data[i]!="undefined"){
                    padding = "padding-top: 0px;";
                    if(i==0){
                        padding = "padding-top: 5px;";
                    }
                    if(data[i]['type']==1){
                        //console.log(data[i])
                        link =                  '<li><a href="post?view_type=view_post&postID='+ data[i]['link'] +'" title="" data-original-title="">'+ data[i]['first_name'] +' '+ data[i]['last_name'] +'</a></li>';
                        icon = "icon-file";
                    }else{
                        link =                  '<li><a href="/workspace?view_type=request&formID='+ data[i]['ws_id'] +'&requestID='+ data[i]['data_id'] +'" title="" data-original-title="">'+ data[i]['first_name'] +' '+ data[i]['last_name'] +'</a></li>';
                        icon = "icon-reorder";
                    }
                    ret += '<div class="supTicket nobg starred-row" style="'+ padding +'">';
                    ret +=        '<div class="pull-right" style="right: 25px;height:12px"><i class="icon-remove cursor removeStarred" data-starred="'+ data[i]['starred_id'] +'" style="display:none" data-type="'+ data[i]['type'] +'" data-id="'+ data[i]['starred_id'] +'" counterPart-id="starred_'+ data[i]['data_id'] +'" post-id="'+ data[i]['data_id'] +'"></i></div>';
                    ret +=        '<div class="issueType" style="margin-top: 12px;">';
                    ret +=           '<span class="issueInfo" style="width: 70%;"><i class="'+ icon +'"></i> '+ data[i]['form_name'] +'</span>';
                    ret +=           '<span class="issueNum" style="float:left">'+ if_undefinded(data[i]['TrackNo'],"") +'</span>';
                    ret +=        '</div>';
                    ret +=        '<div class="issueSummary">';
                    ret +=           '<a href="#" title="" class="pull-left" data-original-title="">';
                    ret +=              data[i]['user_image'];
                    ret +=            '</a>';
                    ret +=           '<div class="ticketInfo">';
                    ret +=              '<ul>';
                    ret += link;
                    stat = 'Status: <strong class="green">'+ data[i]['form_status'] +'</strong>';
                    if(data[i]['form_status']==undefined){
                        stat = "<br />";
                    }
                    ret +=                  '<li>'+ stat +'</li>';
                    ret +=                  '<li class="even timeago" style="font-size: 10px;text-align: left;color: #888888;text-align:left">'+ data[i]['DateCreated'] +'</li>';
                    // ret +=                  '<li><a style="font-size: 11px;cursor: pointer;">Remove</a></li>'
                    ret +=               '</ul>';
                    ret +=            '</div>';
                    ret +=         '</div>';
                    ret +=     '</div>';
                    ret +=    '<div class="hr" style=""></div>';    
                }
                
            }
            // })             
        }
        return ret;
    },
    view2 : function(data){
        var ret = "";
        var stat = "";
        if(data.length==0){
            continueToLoad_starred = false;
        }else{
            // $.each(data,function(key, request){

            var requestor_id = "";
            var padding = "";
            var link = "";
            var icon = "";
            var dataText = "";
            var form_json = "";
            var header_info = "";
            for(var i in data){
                if(data[i]!="undefined"){
                    //For Request
                    if(data[i]['TrackNo']){
                        form_json = data[i]['form_json'];
                        if(form_json){
                            form_json = JSON.parse(form_json);
                            dataText = data[i]['first_name'] +' '+ data[i]['last_name']+" : ";
                            dataText += "Tracking Number : "+data[i]['TrackNo']+", Status : "+data[i]['TrackNo']+", Date Created : "+data[i]['DateCreated']+", ";
                            if(form_json['form_json']['collected_data_header_info']){
                                header_info = form_json['form_json']['collected_data_header_info']['listedchoice'];
                                for(var j in header_info){
                                    dataText += header_info[j]['field_label']+" : "+data[i][''+ header_info[j]['field_name'] +'']+" ";
                                    if(j<header_info.length){
                                        dataText+=", ";
                                    }
                                }
                            }
                        }
                        link = '<a href="/user_view/workspace?view_type=request&formID='+ data[i]['ws_id'] +'&requestID='+ data[i]['data_id'] +'" title="" data-original-title="" style="color:#ffffff">Request</a>';
                        dataText = this.limitText(dataText,150);
                    }else{
                        //For Announcement / Post
                        link = '<a href="post?view_type=view_post&postID='+ data[i]['link'] +'" title="" data-original-title="" style="color:#ffffff">Announcements</a>';
                        dataText = this.limitText(data[i]['first_name'] +' '+ data[i]['last_name']+": "+replaceTagStr(replaceStrHashtags_decode(replaceStrHashtags_encode(replaceURLWithHTMLLinks(data[i]['post'])),1)),100);
                    }
                    ret +=    '<li>';
                        ret +=    '<div class="fl-status-and-type">';
                            ret +=    '<i class="fa fa-star fl-starred-color"></i>';
                            ret +=    '<span class="fl-from">'+ link +'</span>';
                        ret +=    '</div>';
                        ret +=    '<div class="fl-notification-content">';
                            ret +=    dataText;
                            ret += "";
                        ret +=    '</div>';
                        ret +=    '<div class="fl-notification-del-time">';
                            ret +=    '<span class="fl-delete">';
                                ret +=    '<i class="fa fa-trash-o removeStarred_user" data-starred="'+ data[i]['starred_id'] +'" data-type="'+ data[i]['type'] +'" data-id="'+ data[i]['starred_id'] +'" counterPart-id="starred_'+ data[i]['data_id'] +'" post-id="'+ data[i]['data_id'] +'"></i>';
                            ret +=    '</span> ';
                            ret +=    '<span class="time">'+ data[i]['DateCreated'] +'</span>';
                        ret +=    '</div>';
                        ret +=    '<div class="clearfix"></div>';
                    ret +=    '</li>';
                }
                
            }
            // })             
        }
        return ret;
    },
    view3 : function(data){
        var ret = "";
        var stat = "";
        if(data.length==0){
            continueToLoad_starred = false;
        }else{
            // $.each(data,function(key, request){

            var requestor_id = "";
            var padding = "";
            var link = "";
            var icon = "";
            var lengthStarredWidget = $(".starredUserWidgetWrapper").find(".fl-widget-content").length;
            for(var i in data){
                if(data[i]!="undefined"){
                    if(lengthStarredWidget>=10){
                        continueToLoad_starred = false;
                        break;
                    }
                    // padding = "padding-top: 0px;";
                    // if(i==0){
                    //     padding = "padding-top: 5px;";
                    // }
                    // if(data[i]['type']==1){
                    //     //console.log(data[i])
                    //     link =                  '<li><a href="post?view_type=view_post&postID='+ data[i]['link'] +'" title="" data-original-title="">'+ data[i]['first_name'] +' '+ data[i]['last_name'] +'</a></li>';
                    //     icon = "icon-file";
                    // }else{
                    //     link =                  '<li><a href="/workspace?view_type=request&formID='+ data[i]['ws_id'] +'&requestID='+ data[i]['data_id'] +'" title="" data-original-title="">'+ data[i]['first_name'] +' '+ data[i]['last_name'] +'</a></li>';
                    //     icon = "icon-reorder";
                    // }
                    // ret += '<div class="supTicket nobg starred-row" style="'+ padding +'">';
                    // ret +=        '<div class="pull-right" style="right: 25px;height:12px"><i class="icon-remove cursor removeStarred" data-starred="'+ data[i]['starred_id'] +'" style="display:none" data-type="'+ data[i]['type'] +'" data-id="'+ data[i]['starred_id'] +'" counterPart-id="starred_'+ data[i]['data_id'] +'" post-id="'+ data[i]['data_id'] +'"></i></div>';
                    // ret +=        '<div class="issueType" style="margin-top: 12px;">';
                    // ret +=           '<span class="issueInfo" style="width: 70%;"><i class="'+ icon +'"></i> '+ data[i]['form_name'] +'</span>';
                    // ret +=           '<span class="issueNum" style="float:left">'+ if_undefinded(data[i]['TrackNo'],"") +'</span>';
                    // ret +=        '</div>';
                    // ret +=        '<div class="issueSummary">';
                    // ret +=           '<a href="#" title="" class="pull-left" data-original-title="">';
                    // ret +=              data[i]['user_image'];
                    // ret +=            '</a>';
                    // ret +=           '<div class="ticketInfo">';
                    // ret +=              '<ul>';
                    // ret += link;
                    // stat = 'Status: <strong class="green">'+ data[i]['form_status'] +'</strong>';
                    // if(data[i]['form_status']==undefined){
                    //     stat = "<br />";
                    // }
                    // ret +=                  '<li>'+ stat +'</li>';
                    // ret +=                  '<li class="even timeago" style="font-size: 10px;text-align: left;color: #888888;text-align:left">'+ data[i]['DateCreated'] +'</li>';
                    // // ret +=                  '<li><a style="font-size: 11px;cursor: pointer;">Remove</a></li>'
                    // ret +=               '</ul>';
                    // ret +=            '</div>';
                    // ret +=         '</div>';
                    // ret +=     '</div>';
                    // ret +=    '<div class="hr" style=""></div>';    
                    // console.log(data[i])
                    var starred_type = '<a href="/user_view/post?view_type=view_post&postID='+ data[i]['link'] +'" title="" data-original-title="">Announcements</a>';
                    if(data[i]['TrackNo']){
                        starred_type = '<a href="/user_view/workspace?view_type=request&formID='+ data[i]['ws_id'] +'&requestID='+ data[i]['data_id'] +'" title="" data-original-title="">Request</a>';
                    }
                    ret +=    '<div class="fl-widget-content">';
                      ret +=    '<div class="fl-avatar">'+ data[i]['user_image'] +'</div>';
                      ret +=    '<div class="fl-widget-starred-content-wrapper">';
                        ret +=    '<i class="fl-delete fa fa-times removeStarred_user_widget" data-starred="'+ data[i]['starred_id'] +'" data-type="'+ data[i]['type'] +'" data-id="'+ data[i]['starred_id'] +'" counterPart-id="starred_'+ data[i]['data_id'] +'" post-id="'+ data[i]['data_id'] +'"></i>';
                        ret +=    '<span class="starredtype-data theme-font-color">'+ starred_type +'</span><br/>';
                        ret +=    '<span class="starredname-data">'+ data[i]['first_name'] +' '+ data[i]['last_name'] +'</span><br/>';
                        ret +=    '<span class="starreddate-data">'+ data[i]['DateCreated'] +'</span>';
                      ret +=    '</div>';
                      ret +=    '<div class="clearfix"></div>';
                   ret +=    '</div>';
                }
                
            }
            // })             
        }
        return ret;
    },
    count : function(){
        $.post("/ajax/starred",{action:"countData"},function(data){
            $("#starred_count").text(data);
            $(".starred_count").text(data);
        })
        // .fail(function(){
        //     alert("CONNECTION FAILED!!");
        //     $("#starred_count").text("0");
        // })
    },
	 // Set Starred hover
    hoverIn : function(obj){
        var data_starred = $(obj).attr("data-starred");
        if(data_starred==0){
            $(obj).removeClass('icon-star-empty').addClass("icon-star");
        }
    },
    hoverOut : function(obj){
    	var data_starred = $(obj).attr("data-starred");
        if(data_starred==0){
        	$(obj).removeClass('icon-star').addClass("icon-star-empty");
        }
    },
    updateData : function(obj,ele_id){
    	var data_starred = $(obj).attr("data-starred");
        var data_type = $(obj).attr("data-type");
    	var tablename = $(obj).closest(".fl-table-wrapper").find(".table-name").val();
        if(tablename!=""){
            tablename = $(".table-name").val();
        }
    	var data_id = $(obj).attr("data-id");
        var post_id = $(obj).attr("post-id");
        // alert("data_starred = "+data_starred+"\ndata_type = "+data_type+"\ntablename = "+tablename+"\ndata_id = "+data_id+"\npost_id = "+post_id)
        // return;
    	$.post("/ajax/starred",{action:"updateData",
    					data_starred:data_starred,tablename:tablename,
    					data_id:data_id},function(data){
    		data = JSON.parse(data);
            if($(obj).hasClass("removeStarred_user")){
                $(obj).closest("li").fadeOut();
            }else if($(obj).hasClass("removeStarred_user_widget")){
                $(obj).closest(".fl-widget-content").fadeOut();
            }else{
                if(data['status']=="added"){
                    $("#"+ele_id).attr("data-starred",data['id']);
                    $("#"+ele_id).removeClass('icon-star-empty');
                    $("#"+ele_id).addClass('icon-star');
                    if($(obj).hasClass("fa-star-o")){
                        $("#"+ele_id).removeClass('fa-star-o');
                        $("#"+ele_id).addClass('fa-star');
                    }
                }else{
                    $("#"+ele_id).attr("data-starred","0");
                    $("#"+ele_id).toggleClass('icon-star icon-star-empty');
                    if($(obj).hasClass("fa-star")){
                        $("#"+ele_id).removeClass('fa-star');
                        $("#"+ele_id).addClass('fa-star-o');
                    }
                }
                if(data_type==1){
                    $(".starred_show_" + post_id).hide();
                    var ret = '<div class=" postPrivacyChoice-choices post_starred" id="addStarred_' + post_id + '" data-action="addStarred" data-id="' + post_id + '" style="">';
                        ret += '<span class="postChoice-icon" style="">';
                            ret += '<i class=" icon-star-empty" style=""></i>';
                        ret += '</span>';
                        ret += '<span class="postChoice" value="0" style="float: left;">Starred Post</span>';
                    ret += '</div>';    
                    $("#postSettingChoice_"+post_id).html(ret)
                }
            }
            //showNotification({
			//     message: data['message'],
	        //     type: "success",
			//     autoClose: true,
			//     duration: 3
			//})
    	})
    },
    loadAfterAjaxStarredWidget : function(result){
        $(".sub-container-starred").html(result);
        if(result.length>0 && $(".sm-sr").length==0){
            $(".sub-container-starred").append("<div class='sm-sr' style='margin-top: 50px;padding: 0px 0px 10px 0px;text-align:center;font-weight: bold;'><a href='/starred'>See All</a></div>");
        }
        $("#starred-container").perfectScrollbar();
        $("#starred-container").perfectScrollbar("update");

        //user widget
        $(".starredUserWidgetWrapper").perfectScrollbar();
        $(".starredUserWidgetWrapper").perfectScrollbar("update");
        this.count();
    },
    limitText : function(str,length){
        var strlength = str.length;
        var ret = ""
        ret =  str.substr(0,length);
        if(strlength>length){
            ret+= "..";
        }
        return ret;
    }
}